import numpy as np
import cv2
import tensorflow as tf  
class Point(object):
    def __init__(self,x,y):
        self.x = x
        self.y = y
 
    def getX(self):
        return self.x
    def getY(self):
        return self.y
 
def getGrayDiff(img,currentPoint,tmpPoint):
    return abs(int(img[currentPoint.x,currentPoint.y]) - int(img[tmpPoint.x,tmpPoint.y]))
 
def selectConnects(p):
    if p != 0:
        connects = [Point(-1, -1), Point(0, -1), Point(1, -1), Point(1, 0), Point(1, 1), \
                    Point(0, 1), Point(-1, 1), Point(-1, 0)]
    else:
        connects = [ Point(0, -1),  Point(1, 0),Point(0, 1), Point(-1, 0)]
    return connects
 
def regionGrow(img,seed, label_img, p = 1):
    '''单个区域扩展'''
    height, weight = img.shape
    seedList = []
    region = []
    seedList.append(seed)
    label = 1
    connects = selectConnects(p)

    if label_img[seedList[0].x, seedList[0].y] == 0:
        return region
    
    while(len(seedList)>0):
        currentPoint = seedList.pop(0)

        label_img[currentPoint.x,currentPoint.y] = 0
        region.append(currentPoint)
        for i in range(8):
            tmpX = currentPoint.x + connects[i].x
            tmpY = currentPoint.y + connects[i].y
            if tmpX < 0 or tmpY < 0 or tmpX >= height or tmpY >= weight:
                continue
            if  label_img[tmpX, tmpY] == 255:
                label_img[tmpX, tmpY] = 0 
                seedList.append(Point(tmpX,tmpY))
                region.append(Point(tmpX,tmpY))
    #print("get_region!")

    return region

def image_region(img, target_thresh):
    '''整个图像区域统计'''
    label_img = img
    [seed_x, seed_y] = np.where(img > 0)
    seed_length = len(seed_x)
    true_region = []
    false_region = []
    for i in range(seed_length):
        region = regionGrow(img, Point(seed_x[i], seed_y[i]), label_img)
        if len(region) == 0: 
            continue
        elif len(region) > target_thresh:
            true_region.append(region)
            print("true_region-------->",len(true_region))
        else:
            false_region.append(region)
            #print("false_region-------->",len(false_region))

    print(len(true_region))

    mark_img = np.zeros(img.shape)
    for region in true_region:
        for point in region:
            mark_img[point.x, point.y] = 255
    return true_region, false_region, mark_img

def get_region_center(region):
    '''得到区域中心'''
    m10 = 0           #x矩
    m01 = 0           #y矩
    miu11 = 0         #1+1中心距
    miu02 = 0         #0+2中心距
    miu20 = 0         #2+0中心距
    area = len(region)
    print(area)
    for point in region:
        m10 = m10 + point.x
        m01 = m01 + point.y
    
    m10 = m10/area
    m01 = m01/area
    center = Point(round(m10), round(m01))
    print("center:("+str(round(m10))+", "+ str(round(m01))+")")
    return center

def get_distance(Px, Py):
    '''两点之间距离'''
    return np.sqrt( (Px.x - Py.x)**2 + (Px.y - Py.y)**2)

def gather_region(region_center, thresh):
    '''聚集区域'''
    change = 0
    new_center = region_center

    while(True):
        length = len(new_center) 
        for i in range(length):
            for j in range(i+1, length):
                if get_distance(new_center[i], new_center[j]) <= thresh :
                    new_x = round((new_center[i].x + new_center[j].x)/2)
                    new_y = round((new_center[i].y + new_center[j].y)/2)
                    new_center.append(Point(new_x, new_y))
                    print("("+str(new_center[i].x)+", "+str(new_center[i].y)+")"+
                    "("+str(new_center[j].x)+", "+str(new_center[j].y)+")"+" change------>", "("+str(new_x)+", "+str(new_y))
                    del new_center[i]
                    del new_center[j]
                    change = 1
                    
                    break
            if change == 1:
                break
        if(change == 1):
            change = 0
        else:
            break
    print(len(new_center))
    for point in new_center:
        print("new center:("+str(point.x)+", "+ str(point.y)+")")
    return new_center


def main():

    img = cv2.imread('C:/Users/wangdi/Desktop/Prob4.jpeg')
    image = tf.io.read_file('C:/Users/wangdi/Desktop/crop4.jpeg')
    image = tf.image.decode_jpeg(image)
    
    print(img.shape)
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    img2 = cv2.imread('C:/Users/wangdi/Desktop/crop4.jpeg')
    print(gray.shape)
    
    true_region, false_region, mark_img = image_region(gray, 100)
    
    region_center = []
    for region in true_region:
        region_center.append(get_region_center(region))
    new_center = gather_region(region_center, 25)

    
    i = 0
    center_array = np.zeros((len(new_center), 2))
    for point in new_center:
        center_array[i][0] = point.x
        center_array[i][1] = point.y
        cv2.circle(img2, (point.y+32, point.x+32), 1, (0,0,255),8)
        cv2.rectangle(img2, (point.y+32-44, point.x+32-44), (point.y+32+44, point.x+32+44), (0, 255, 255), 1)
        crop_img = tf.image.crop_to_bounding_box(image, point.x+32-44, point.y+32-44, 88, 88)
        crop_img = tf.image.encode_jpeg(crop_img)
        with tf.io.gfile.GFile('E:/大学课程资料/大四上/毕业设计/MSTAR_Clutter/crop_target/target-'+ str(i) + '.jpeg','wb') as file:
            file.write(crop_img.numpy())
            i = i + 1
    np.savetxt('E:/大学课程资料/大四上/毕业设计/MSTAR_Clutter/center_array.txt',center_array)
    cv2.imshow(' ',img2)
    cv2.imwrite('C:/Users/wangdi/Desktop/target_ATR.jpg', img2)
    
    #cv2.imencode('.jpg', mark)[1].tofile('E:/大学课程资料/大四上/毕业设计/MSTAR_Clutter/region.jpeg')
    
    
    cv2.waitKey(0)
    #seeds = [Point(10,10),Point(82,150),Point(20,300)]
    #binaryImg = regionGrow(img,seeds,10)
    #cv2.imshow(' ',binaryImg)
    #cv2.waitKey(0)


if __name__ == '__main__':
    main()

    